using System.Collections.Generic;
using UnityEngine;

namespace Game.Tile
{
    /// <summary>
    ///     让 Tile 置顶显示
    /// </summary>
    public class TileTop
    {
        /// <summary>
        ///     此列表将跟踪我们想要排序的所有精灵渲染器
        /// </summary>
        private readonly List<SpriteRenderer> mSortIndices = new();

        private static void SetRenderOrder(SpriteRenderer renderer, int index)
        {
            renderer.sortingOrder = index;
            var p = renderer.transform.position;
            p.z = -index / 10.0f;
            renderer.transform.position = p;
        }

        public void BringToTop(SpriteRenderer renderer)
        {
            Remove(renderer);
            Add(renderer);
        }

        private void Add(SpriteRenderer renderer)
        {
            mSortIndices.Add(renderer);
            SetRenderOrder(renderer, mSortIndices.Count);
        }

        private void Remove(SpriteRenderer renderer)
        {
            mSortIndices.Remove(renderer);
            for (var i = 0; i < mSortIndices.Count; i++) SetRenderOrder(mSortIndices[i], i + 1);
        }

        public void Clear()
        {
            mSortIndices.Clear();
        }
    }
}